package com.neusoft.neuiotms.dcom.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.dto.result.PageResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.bean.ProjectUserBean;
import com.neusoft.neuiotms.dcom.dto.QuestionnaireFeedbackDTO;
import com.neusoft.neuiotms.dcom.service.InstitutionsService;
import com.neusoft.neuiotms.dcom.service.QuestionnaireFeedbackService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "总结报告不管理")
@RestController
@RequestMapping(value = "/api/w/feedbacks")
public class QuestionnaireFeedbackController {

    @Autowired
    private QuestionnaireFeedbackService questionnaireFeedbackService;
    @Autowired
    private InstitutionsService institutionsService;

    @ApiOperation("查询所有总结报告")
    @GetMapping
    public ResultListDTO<QuestionnaireFeedbackDTO> index(final Searchable searchable, final UserBean userBean) {
        return ResultListDTO.success(this.questionnaireFeedbackService.index(searchable, userBean));
    }

    @ApiOperation("分页查询所有总结报告")
    @GetMapping("/p")
    public PageResultDTO<QuestionnaireFeedbackDTO> search(final Pageable pageable, final Searchable searchable,
            final UserBean userBean) {
        return PageResultDTO.success(this.questionnaireFeedbackService.search(pageable, searchable, userBean));
    }

    @ApiOperation("创建报告")
    @PostMapping
    public ResultDTO<QuestionnaireFeedbackDTO> create(@RequestBody final QuestionnaireFeedbackDTO dto,
            final UserBean userBean) {
        final ProjectUserBean projectInfo = this.institutionsService.getMyInstitutions(userBean);

        dto.setUsername(userBean.getUsername());
        dto.setUser(userBean.getName());
        dto.setGroupCode(projectInfo.getGroupCode());
        dto.setGroupName(projectInfo.getGroupName());
        dto.setInstitutionCode(projectInfo.getDefaultInstituteCode());
        dto.setInstitutionName(projectInfo.getDefaultInstituteName());

        return ResultDTO.success(this.questionnaireFeedbackService.create(dto));
    }

    @ApiOperation(value = "修改报告")
    @RequestMapping(path = "/{id}", method = {RequestMethod.PUT, RequestMethod.POST })
    public ResultDTO<QuestionnaireFeedbackDTO> update(@PathVariable final Long id,
            @RequestBody final QuestionnaireFeedbackDTO dto) {
        return ResultDTO.success(this.questionnaireFeedbackService.update(id, dto));
    }

    @ApiOperation("报告详情")
    @GetMapping("/{id}")
    public ResultDTO<QuestionnaireFeedbackDTO> details(@PathVariable final Long id, final UserBean userBean) {
        return ResultDTO.success(this.questionnaireFeedbackService.details(id, userBean));
    }

    @ApiOperation("报告详情")
    @GetMapping("/task/{taskId}")
    public ResultDTO<QuestionnaireFeedbackDTO> detailsByTask(@PathVariable final Long taskId, final UserBean userBean) {
        return ResultDTO.success(this.questionnaireFeedbackService.detailsByTask(taskId, userBean));
    }

    @ApiOperation("删除报告")
    @DeleteMapping("/{id}")
    public ResultDTO<Void> delete(@PathVariable final Long id) {
        this.questionnaireFeedbackService.delete(id);
        return ResultDTO.success();
    }

    @RequestMapping(path = "/{id}/submit", method = {RequestMethod.PUT, RequestMethod.POST })
    public ResultDTO<?> submit(@PathVariable final Long id,
            final UserBean userBean) {
        final boolean result = this.questionnaireFeedbackService.submit(id);
        return ResultDTO.success(result);
    }

    @PutMapping("/{id}/rollback")
    public ResultDTO<?> rollback(@PathVariable final Long id,
            final UserBean userBean) {
        final boolean result = this.questionnaireFeedbackService.rollback(id);
        return ResultDTO.success(result);
    }

    @ApiOperation("工作总结统计报表")
    @GetMapping("/stats/report")
    public PageResultDTO<?> reportStats(final Pageable pageable, final UserBean userBean,
            @RequestParam(required = false) final String type,
            @RequestParam(required = false) final String username,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date start,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date end) {

        final ProjectUserBean projectInfo = this.institutionsService.getMyInstitutions(userBean);
        final Page<Map<String, Object>> result =
                this.questionnaireFeedbackService.report(pageable, projectInfo.getGroupCode(), username, type, start,
                        end);
        return PageResultDTO.success(result);
    }

    @ApiOperation("导出工作总结统计")
    @GetMapping(value = "/stats/export")
    public void exportStats(final UserBean userBean, @RequestParam(required = false) final String type,
            @RequestParam(required = false) final String username,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date start,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date end,
            final HttpServletResponse response) {

        final ProjectUserBean projectInfo = this.institutionsService.getMyInstitutions(userBean);
        final Workbook workbook =
                this.questionnaireFeedbackService.exportReport(projectInfo.getGroupCode(), username, type, start, end);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("工作总结统计导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            QuestionnaireFeedbackController.log.error("工作总结统计导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                QuestionnaireFeedbackController.log.error("工作总结统计导出关闭流失败", e);
            }
        }
    }

    @ApiOperation("导出工作总结")
    @GetMapping(value = "/export/{id}")
    public void download(@PathVariable final Long id, final HttpServletResponse response, final UserBean userBean) {

        final QuestionnaireFeedbackDTO dto = this.questionnaireFeedbackService.details(id, userBean);
        final XWPFDocument xfc = this.questionnaireFeedbackService.export(id, userBean);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode(
                                    dto.getQuestionnaire().getTitle() + "-" + dto.getUser() + "-"
                                            + DateFormatUtils.format(dto.getSubmitAt(), "yyyy-MM-dd") + ".docx",
                                    "UTF-8")));
            xfc.write(out);
            out.flush();
        } catch (final Exception e) {
            QuestionnaireFeedbackController.log.error("工作总结导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                QuestionnaireFeedbackController.log.error("工作总结导出关闭流失败", e);
            }
        }
    }
}
